<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ESP8266设备配置</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: #333;
            line-height: 1.6;
            padding: 20px;
            min-height: 100vh;
        }

        .container {
            max-width: 500px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 1.8rem;
            margin-bottom: 8px;
            text-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }

        .header p {
            font-size: 1rem;
            opacity: 0.9;
        }

        .config-card {
            background: white;
            border-radius: 16px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            transition: transform 0.3s ease;
        }

        .config-card:hover {
            transform: translateY(-5px);
        }

        .card-title {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            color: #2c3e50;
            font-size: 1.2rem;
        }

        .card-title i {
            margin-right: 10px;
            color: #3498db;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 0.95rem;
        }

        input,
        select {
            width: 100%;
            padding: 14px;
            border: 2px solid #eef2f7;
            border-radius: 10px;
            font-size: 1rem;
            transition: all 0.3s;
            background-color: #f8fafc;
        }

        input:focus,
        select:focus {
            border-color: #3498db;
            background-color: white;
            outline: none;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }

        .btn-group {
            display: flex;
            gap: 15px;
            margin-top: 10px;
        }

        button {
            flex: 1;
            padding: 16px;
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: linear-gradient(to right, #3498db, #2c3e50);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.4);
        }

        .btn-secondary {
            background: #f1f2f6;
            color: #2c3e50;
        }

        .btn-secondary:hover {
            background: #dfe4ea;
        }

        .status {
            text-align: center;
            padding: 15px;
            border-radius: 10px;
            margin-top: 20px;
            display: none;
        }

        .status.success {
            background-color: #d4edda;
            color: #155724;
            display: block;
        }

        .status.error {
            background-color: #f8d7da;
            color: #721c24;
            display: block;
        }

        .status.info {
            background-color: #cce7ff;
            color: #004085;
            display: block;
        }

        .service-status {
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 15px;
            padding: 10px;
            border-radius: 8px;
            font-weight: 600;
        }

        .service-running {
            background-color: #d4edda;
            color: #155724;
        }

        .service-stopped {
            background-color: #f8d7da;
            color: #721c24;
        }

        .service-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .running {
            background-color: #27ae60;
            animation: pulse 1.5s infinite;
        }

        .stopped {
            background-color: #e74c3c;
        }

        @keyframes pulse {
            0% {
                opacity: 1;
            }

            50% {
                opacity: 0.5;
            }

            100% {
                opacity: 1;
            }
        }

        .footer {
            text-align: center;
            margin-top: 30px;
            color: rgba(255, 255, 255, 0.7);
            font-size: 0.9rem;
        }

        @media (max-width: 480px) {
            .container {
                padding: 0 10px;
            }

            .config-card {
                padding: 20px 15px;
            }

            .header h1 {
                font-size: 1.5rem;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <h1>ESP8266设备配置</h1>
            <p>配置WiFi和MQTT连接参数</p>
        </div>

        <form id="configForm">
            <div class="config-card">
                <div class="card-title">
                    <i>📶</i> WiFi设置
                </div>

                <div class="form-group">
                    <label for="wifi_ssid">WiFi名称 (SSID)</label>
                    <input type="text" id="wifi_ssid" name="wifi_ssid" maxlength="19" placeholder="输入WiFi名称" required>
                </div>

                <div class="form-group">
                    <label for="wifi_password">WiFi密码</label>
                    <input type="password" id="wifi_password" name="wifi_password" maxlength="19" placeholder="输入WiFi密码"
                        required>
                </div>
            </div>

            <div class="config-card">
                <div class="card-title">
                    <i>🌐</i> MQTT服务器设置
                </div>

                <div class="form-group">
                    <label for="mqtt_server">MQTT服务器地址</label>
                    <input type="text" id="mqtt_server" name="mqtt_server" maxlength="19"
                        placeholder="例如: 192.168.1.100" required>
                </div>

                <div class="form-group">
                    <label for="mqtt_port">MQTT端口</label>
                    <input type="number" id="mqtt_port" name="mqtt_port" min="1" max="65535" value="1883" required>
                </div>

                <div class="form-group">
                    <label for="mqtt_user">MQTT用户名</label>
                    <input type="text" id="mqtt_user" name="mqtt_user" maxlength="19" placeholder="输入MQTT用户名">
                </div>

                <div class="form-group">
                    <label for="mqtt_password">MQTT密码</label>
                    <input type="password" id="mqtt_password" name="mqtt_password" maxlength="19"
                        placeholder="输入MQTT密码">
                </div>
            </div>

            <div class="config-card">
                <div class="card-title">
                    <i>📡</i> MQTT主题设置
                </div>

                <div class="form-group">
                    <label for="mqtt_pub_topic">发布主题</label>
                    <input type="text" id="mqtt_pub_topic" name="mqtt_pub_topic" maxlength="19"
                        placeholder="例如: device/sensor/data" required>
                </div>

                <div class="form-group">
                    <label for="mqtt_sub_topic">订阅主题</label>
                    <input type="text" id="mqtt_sub_topic" name="mqtt_sub_topic" maxlength="19"
                        placeholder="例如: device/control" required>
                </div>
            </div>

            <div class="config-card">
                <div class="card-title">
                    <i>⚙️</i> 服务状态设置
                </div>

                <div class="form-group">
                    <label for="service_status">服务状态</label>
                    <select id="service_status" name="stopped">
                        <option value="0">运行中</option>
                        <option value="1">已停止</option>
                    </select>
                </div>

                <div id="serviceStatus" class="service-status">
                    <span class="service-indicator stopped"></span>
                    <span>服务状态: 已停止</span>
                </div>
            </div>

            <div class="btn-group">
                <button type="button" class="btn-secondary" id="resetBtn">重置</button>
                <button type="submit" class="btn-primary">保存配置</button>
            </div>
        </form>

        <div id="statusMessage" class="status"></div>

        <div class="footer">
            <p>ESP8266配置界面 &copy; 2025</p>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const form = document.getElementById('configForm');
            const resetBtn = document.getElementById('resetBtn');
            const serviceStatusSelect = document.getElementById('service_status');
            const statusMessage = document.getElementById('statusMessage');
            const serviceStatus = document.getElementById('serviceStatus');

            // 从后台加载配置
            loadConfig();

            // 监听服务状态选择变化
            serviceStatusSelect.addEventListener('change', function () {
                updateServiceStatus(this.value === '0');
            });

            // 重置表单
            resetBtn.addEventListener('click', function () {
                if (confirm('确定要重置所有配置吗？')) {
                    form.reset();
                    statusMessage.className = 'status';
                    statusMessage.textContent = '';
                    updateServiceStatus(false);
                }
            });

            // 表单提交
            form.addEventListener('submit', function (e) {
                e.preventDefault();

                // 验证表单
                if (!validateForm()) {
                    return;
                }

                // 保存配置到后台
                saveConfig();
            });

            // 从后台加载配置
            async function loadConfig() {
                try {
                    showStatus('正在加载配置...', 'info');

                    // 从ESP设备获取配置
                    const response = await fetch('/config');
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    const config = await response.json();

                    // 填充表单
                    document.getElementById('wifi_ssid').value = config.wifi_ssid || '';
                    document.getElementById('wifi_password').value = config.wifi_password || '';
                    document.getElementById('mqtt_server').value = config.mqtt_server || '';
                    document.getElementById('mqtt_port').value = config.mqtt_port || '1883';
                    document.getElementById('mqtt_user').value = config.mqtt_user || '';
                    document.getElementById('mqtt_password').value = config.mqtt_password || '';
                    document.getElementById('mqtt_pub_topic').value = config.mqtt_pub_topic || '';
                    document.getElementById('mqtt_sub_topic').value = config.mqtt_sub_topic || '';
                    document.getElementById('service_status').value = config.stopped || '1';

                    // 更新服务状态显示
                    updateServiceStatus(config.stopped === 0);

                    showStatus('配置加载成功！', 'success');
                } catch (error) {
                    console.error('加载配置失败:', error);
                    showStatus('加载配置失败，请检查设备连接', 'error');
                }
            }

            // 保存配置到后台
            async function saveConfig() {
                try {
                    showStatus('正在保存配置...', 'info');

                    const formData = new FormData(form);
                    const config = {};

                    for (let [key, value] of formData.entries()) {
                        // 将字符串转换为适当类型
                        if (key === 'mqtt_port') {
                            config[key] = parseInt(value);
                        } else if (key === 'stopped') {
                            config[key] = parseInt(value);
                        } else {
                            config[key] = value;
                        }
                    }

                    // 使用FormData提交表单数据

                    // 将配置发送到ESP设备
                    const response = await fetch('/save', {
                        method: 'POST',
                        body: formData
                    });
                    if (!response.ok) {
                        throw new Error('保存配置失败');
                    }

                    showStatus('配置保存成功！', 'success');
                } catch (error) {
                    console.error('保存配置失败:', error);
                    showStatus('保存配置失败，请检查设备连接', 'error');
                }
            }

            // 更新服务状态显示
            function updateServiceStatus(isRunning) {
                const indicator = serviceStatus.querySelector('.service-indicator');
                const statusText = serviceStatus.querySelector('span:last-child');

                if (isRunning) {
                    indicator.className = 'service-indicator running';
                    statusText.textContent = '服务状态: 运行中';
                    serviceStatus.className = 'service-status service-running';
                } else {
                    indicator.className = 'service-indicator stopped';
                    statusText.textContent = '服务状态: 已停止';
                    serviceStatus.className = 'service-status service-stopped';
                }
            }

            // 表单验证
            function validateForm() {
                const wifiSsid = document.getElementById('wifi_ssid').value.trim();
                const wifiPassword = document.getElementById('wifi_password').value.trim();
                const mqttServer = document.getElementById('mqtt_server').value.trim();
                const mqttPort = document.getElementById('mqtt_port').value;
                const mqttPubTopic = document.getElementById('mqtt_pub_topic').value.trim();
                const mqttSubTopic = document.getElementById('mqtt_sub_topic').value.trim();

                if (!wifiSsid) {
                    showStatus('请输入WiFi名称', 'error');
                    return false;
                }

                if (!wifiPassword) {
                    showStatus('请输入WiFi密码', 'error');
                    return false;
                }

                if (!mqttServer) {
                    showStatus('请输入MQTT服务器地址', 'error');
                    return false;
                }

                if (!mqttPort || mqttPort < 1 || mqttPort > 65535) {
                    showStatus('请输入有效的MQTT端口(1-65535)', 'error');
                    return false;
                }

                if (!mqttPubTopic) {
                    showStatus('请输入发布主题', 'error');
                    return false;
                }

                if (!mqttSubTopic) {
                    showStatus('请输入订阅主题', 'error');
                    return false;
                }

                return true;
            }

            // 显示状态消息
            function showStatus(message, type) {
                statusMessage.textContent = message;
                statusMessage.className = 'status ' + type;

                // 5秒后自动隐藏消息
                setTimeout(function () {
                    statusMessage.className = 'status';
                    statusMessage.textContent = '';
                }, 5000);
            }
        });
    </script>
</body>

</html>